package cn.wd.web.interceptor;

import cn.wd.utils.TokenManager;
import cn.wd.vo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(TokenManager.TOKEN_NAME);
        if (StringUtils.hasText(token) && TokenManager.get(token) != null) {
            return true;
        }

        response.setContentType("application/json;charset=UTF-8");
        String ret = JSON.toJSONString(JsonResult.failed(401, "用户尚未认证，请先登录！"));
        response.getWriter().println(ret);
        return false;
    }
}
